package cn.zysheep.controller;

import cn.zysheep.tools.PdfUtil;
import cn.zysheep.tools.ResponseUtil;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/20
 */
@Controller
public class TestWord2Pdf {
    @RequestMapping("/word2pdf")
    public void word2pdf(MultipartFile multipartFile, HttpServletResponse response) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();

        String wordPath = "F:\\接口文档.doc";
        String pdfPath = "F:\\接口文档.pdf";

        PdfUtil.docx2Pdf(new File(wordPath),new File(pdfPath),"doc");
        System.out.println("转换成功");
        File file = new File(pdfPath);
        ResponseUtil.onlineReader(file,response);
        System.out.println("执行完毕");
    }

    @PostMapping("/uploadWord2Pdf")
    @ResponseBody
    public String uploadWord2Pdf(MultipartFile multipartFile, HttpServletResponse response, HttpServletRequest req) throws IOException {

        //使用UUID生成唯一标识文件名
        String randomNumber = UUID.randomUUID().toString().replace("-", "");
        //获取文件的原始名
        String oldFilename = multipartFile.getOriginalFilename();
        //获取文件后缀 .pdf/.docx/.doc
        String extension = oldFilename.substring(oldFilename.lastIndexOf("."));
        //生成新的文件名
        String newFileName = randomNumber + extension;
        String property = System.getProperty("user.dir")+"\\upload";
        // 上传路径
        File dateDir = new File(property);
        if (!dateDir.exists()) {
            //判断目录是否存在，不存在则直接创建
            dateDir.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(dateDir, newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        //  return ResultVO.fail("上传失败");
        }
        //上传完毕，存入数据库中的地址为：
        // String invented_address = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/api/file/" + newFileName;

        // doc docx转pdf在保存地址到数据库中
        if (extension.equals(".doc") || extension.equals(".docx")) {
            // 转换之后的pdf文件
            String newPdfName = randomNumber+".pdf";
            boolean bool = PdfUtil.docx2Pdf(new File(dateDir, newFileName), new File(dateDir, newPdfName), extension);
            return String.valueOf(bool);
        }
        return "ok";
    }
}
